<?php

namespace app\model;

class OrderBomModel extends BaseModel
{
    protected $name = 'dingdan_bom';


    /**
     * Notes: 采购权限-清单列表
     * User: chenLei
     * Date: 9/16/25
     * @param $params
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bomListCg($params)
    {
        $list = $this->where('dingdan_id', $params['id'])->select()->toArray();

        if (count($list) <= 0) {
            $this->error = '没有查询到bom清单';
            return false;
        }

        foreach ($list as $key => &$value) {
            $material = MaterialCategoryModel::where('id', $value['material_id'])
                ->find();
            $value['diff'] = 0;
            if (!empty($material) && $value['material_quantity'] > $material['current_quantity']) {
                $value['diff'] = $material['current_quantity'] - $value['material_quantity'];
            }
            $value['material'] = $material;
        }

        return $list;

    }


    /**
     * Notes: 生成采购订单
     * User: chenLei
     * Date: 9/16/25
     * @param $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createCgOrder($params)
    {
        $list = $this->where('dingdan_id', $params['id'])->select()->toArray();

        if (count($list) <= 0) {
            $this->error = '没有查询到bom清单';
            return false;
        }

        $data = [];
        foreach ($list as $key => $value) {
            $material = MaterialCategoryModel::where('id', $value['material_id'])
                ->find();
            if (!empty($material) && $value['material_quantity'] > $material['current_quantity']) {
                $diff = $value['material_quantity'] - $material['current_quantity'];
                $data[] = [
                    'material_id' => $value['material_id'],
                    'diff' => $diff,
                ];
            }
        }

        if (count($data) <= 0) {
            $this->error = '当前仓库物料足够，不需要多余的采购';
            return false;
        }


        $materialCategoryModel = new MaterialCategoryModel();
        $res = $materialCategoryModel->bomListCg($data);

        if ($res === false) {
            $this->error = $materialCategoryModel->getError();
            return false;
        }

        return true;



    }

}